package com.kyrie.lib_sys.utils.learn.TimeDemo;

import com.kyrie.lib_sys.application.timeApplys.pojo.entity.TimeRecord;
import com.kyrie.lib_sys.application.timeApplys.pojo.entity.ValidationResult;

import java.time.LocalDateTime;
import java.util.List;
import java.util.ArrayList;

/**
 * 工单时间校验工具类 (旧版  功能缺失版)
 *
 * @author heefM
 * @date 2025-
 */
public class TimeValidatorss {

    /**
     * 验证单个时间记录的正确性（支持部分字段为空）
     */
    public static ValidationResult validateSingleRecord(TimeRecord record) {
        ValidationResult result = new ValidationResult();

        // 获取所有非空时间点（按业务顺序）
        List<TimePoint> points = getValidTimePoints(record);

        // 校验时间点顺序
        for (int i = 0; i < points.size() - 1; i++) {
            TimePoint current = points.get(i);
            TimePoint next = points.get(i + 1);

            if (!next.time.isAfter(current.time)) {
                result.addError(String.format("%s(%s) 不能晚于 %s(%s)",
                        current.fieldName, current.time,
                        next.fieldName, next.time));
            }
        }

        return result;
    }

    /**
     * 验证多个时间记录（支持与已有记录比对）
     */
    public static ValidationResult validateMultipleRecords(
            List<TimeRecord> newRecords,
            List<TimeRecord> existingRecords) {

        ValidationResult result = new ValidationResult();

        // 1. 校验每个新记录内部时间顺序
        for (int i = 0; i < newRecords.size(); i++) {
            ValidationResult singleResult = validateSingleRecord(newRecords.get(i));
            if (!singleResult.isValid()) {
                result.addError("新记录" + (i + 1) + ": " +
                        String.join(", ", singleResult.getErrors()));
            }
        }

        // 2. 校验新记录之间的时间重叠
        checkOverlaps(newRecords, "新记录", result);

        // 3. 校验新记录与已有记录的时间重叠
        if (existingRecords != null && !existingRecords.isEmpty()) {
            checkOverlapsBetweenLists(newRecords, existingRecords, result);
        }

        return result;
    }

    /**
     * 获取有效时间点（非空字段）
     */
    private static List<TimePoint> getValidTimePoints(TimeRecord record) {
        List<TimePoint> points = new ArrayList<>();

        addIfNotNull(points, "prepareTime", record.getPrepareTime());
        addIfNotNull(points, "travelTime", record.getTravelTime());
        addIfNotNull(points, "startTime", record.getStartTime());
        addIfNotNull(points, "completeTime", record.getCompleteTime());

        return points;
    }

    private static void addIfNotNull(List<TimePoint> list, String fieldName, LocalDateTime time) {
        if (time != null) {
            list.add(new TimePoint(fieldName, time));
        }
    }

    /**
     * 检查同一列表内的记录重叠
     */
    private static void checkOverlaps(List<TimeRecord> records, String recordType,
                                      ValidationResult result) {
        for (int i = 0; i < records.size(); i++) {
            TimeRange range1 = getTimeRange(records.get(i));
            if (range1 == null) continue;

            for (int j = i + 1; j < records.size(); j++) {
                TimeRange range2 = getTimeRange(records.get(j));
                if (range2 == null) continue;

                if (isOverlap(range1, range2)) {
                    result.addError(String.format(
                            "%s%d[%s ~ %s]与%s%d[%s ~ %s]存在时间重叠",
                            recordType, i + 1, range1.start, range1.end,
                            recordType, j + 1, range2.start, range2.end
                    ));
                }
            }
        }
    }

    /**
     * 检查两个列表间的记录重叠
     */
    private static void checkOverlapsBetweenLists(
            List<TimeRecord> list1, List<TimeRecord> list2,
            ValidationResult result) {

        for (int i = 0; i < list1.size(); i++) {
            TimeRange range1 = getTimeRange(list1.get(i));
            if (range1 == null) continue;

            for (int j = 0; j < list2.size(); j++) {
                TimeRange range2 = getTimeRange(list2.get(j));
                if (range2 == null) continue;

                if (isOverlap(range1, range2)) {
                    result.addError(String.format(
                            "新记录%d[%s ~ %s]与已有记录%d[%s ~ %s]存在时间重叠",
                            i + 1, range1.start, range1.end,
                            j + 1, range2.start, range2.end
                    ));
                }
            }
        }
    }

    /**
     * 获取有效时间范围（需要prepareTime和completeTime都存在）
     */
    private static TimeRange getTimeRange(TimeRecord record) {
        if (record.getPrepareTime() == null || record.getCompleteTime() == null) {
            return null;
        }
        return new TimeRange(record.getPrepareTime(), record.getCompleteTime());
    }

    /**
     * 判断两个时间范围是否重叠
     */
    private static boolean isOverlap(TimeRange r1, TimeRange r2) {
        return r1.start.isBefore(r2.end) && r2.start.isBefore(r1.end);
    }

    // 辅助内部类
    private static class TimePoint {
        String fieldName;
        LocalDateTime time;

        TimePoint(String fieldName, LocalDateTime time) {
            this.fieldName = fieldName;
            this.time = time;
        }
    }

    private static class TimeRange {
        LocalDateTime start;
        LocalDateTime end;

        TimeRange(LocalDateTime start, LocalDateTime end) {
            this.start = start;
            this.end = end;
        }
    }


}